<template>
  <!-- 最外层框 -->
  <div class="chat flex items-center justify-center w-full">
    <div class="outBorder">
      <div class="title" v-if="chatType == 1">{{ chatPerson[0].nickName }}</div>
      <div class="title" v-else-if="chatType == 2">群聊</div>

      <!-- tab栏 -->
      <div v-if="chatType == 2" class="pl-20 pr-20 tabs-box">
        <el-tabs v-model="activeName" class="" @tab-click="handleClick">
          <el-tab-pane label="聊天" name="chat"></el-tab-pane>
          <el-tab-pane label="公告" name="notice"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="flex" :class="chatType == 1 ? 'bottom-box1' : 'bottom-box2'">
        <div :class="chatType == 1 ? 'bottom-left-box1' : 'bottom-left-box2'">
          <!-- :style="chatType == 1 ? 'width:100%' : 'width:70%'" -->
          <!-- 聊天框 -->
          <div class="dialog-box" :style="chatType == 1 ? 'height:80%' : ''">
            <el-scrollbar v-auto-animate id="scrollbar" ref="scrollbarRef">
              <div class="dialog-box-in" ref="innerRef">
                <div v-for="(v, i) in chatData" :key="i" class="">
                  <div v-if="v.type == 1" class="flex justify-between mb-10">
                    <div></div>
                    <div class="dialog-box-my">
                      <div class="arrowbox-right">
                        {{ v.content }}
                      </div>
                      <el-avatar :src="personalData.avatar" icon="UserFilled" />
                    </div>
                  </div>
                  <div v-if="v.type == 2" class="dialog-box-other mb-10">
                    <el-avatar :src="chatPerson[0].avatar" icon="UserFilled" />
                    <div class="arrowbox-left">
                      {{ v.content }}
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- 输入框 -->
          <div class="input-box-out">
            <div class="input-box">
              <el-scrollbar>
                <el-input
                  v-model="input"
                  type="textarea"
                  autosize
                  placeholder=""
                />
              </el-scrollbar>
              <!-- <textarea class="jh-input" :value="input" autocomplete="off" /> -->
            </div>

            <div class="flex justify-between mt-5 mr-15">
              <div></div>
              <div>
                <el-button plain @click="back()">后退</el-button>
                <el-button plain text bg @click="submit(input)">发送</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 成员列表 -->
        <div :class="chatType == 1 ? '' : 'member-box'">
          <!-- <div v-if="chatType == 1">
            <el-avatar :size="50" :src="chatPerson[0].avatar" />
            {{ chatPerson[0].name }}
          </div> -->

          <el-scrollbar v-if="chatType == 2">
            <p v-for="item in 30" :key="item" class="scrollbar-demo-item">
              {{ item }}
            </p>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { TabsPaneContext } from "element-plus";
import { ElScrollbar } from "element-plus";

import Utils from "@/utils";
import io from "socket.io-client";
import { useRouter } from "vue-router";
let router = useRouter();

/* 个人数据 */
let personalData = Utils.getSession("personalData")[0];

/* 上方tabs */
const activeName = ref("chat");
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

/* 聊天类型
 *  1. 单人聊天
 *  2. 群组聊天
 */
let chatType = ref(1);

/* 当前聊天的人
  序号            id
  昵称            name
  性别            sex
    1. 男
    2. 女
  头像            avatar
  个人简介        intro
*/
let chatPerson: any[] = reactive([]);
/* 单人情况 */
let friendList: any = router.currentRoute.value.query.friendList;
chatPerson.push(JSON.parse(friendList));
/* 群组情况 */
// TODO 后续添加群组

/* 聊天数据
  序号              id

  ！  如果是私聊 那只有用户id
  ！  如果是群聊 那有用户id 和 群id
  用户id            userId
  群id              groupId

  内容              content

  类型              type
  1. 自己
  2. 别人
*/
let chatData: any[] = reactive([]);
// TODO 后续后端增加获取历史记录接口

/* 下方输入框 */
let input = ref("");
const innerRef = ref<HTMLDivElement>();
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();

// 定义房间名称
/* 私聊名称 */
var roomName = `pensonChat${chatPerson[0].roomId}`;
/* 群聊名称 */

/* 发送消息 */
const submit = (word: string) => {
  if (!!word) {
    let data = {
      userId: personalData.id,
      groupId: -1,
      content: word,
      // type: 1,
      userFriendsId: "",
      roomName: "",
    };
    data.roomName = roomName;

    /* 1 为 私人聊天 ，2 为 群组聊天 */
    if (chatType.value == 1) {
      data.groupId = -1;
      data.userFriendsId = chatPerson[0].roomId;
    } else if (chatType.value == 2) {
      data.groupId = 1;
    }
    // 向服务器发出 'chatMessage' 事件
    socket.emit("chatMessage", data);
    // chatData.push(data);

    input.value = "";

    Utils.slideToBottom(innerRef, scrollbarRef);
  }
};

Utils.slideToBottom(innerRef, scrollbarRef);

/* 快捷键发送 */
document.addEventListener("keydown", (e: any) => {
  if (e.ctrlKey && e.code == "Enter") {
    submit(input.value);
  }
});

let back = () => {
  router.go(-1);
};

// 创建一个 Socket.IO 实例并连接到服务器
const socket = io("http://localhost:3001");

// 监听 'connect' 事件
socket.on("connect", () => {
  console.log("已连接到服务器");
  // 监听 'message' 事件
});

socket.on("message", (data: any) => {
  console.log("收到一条消息：", data);
  if (data.userId == personalData.id) {
    data.type = 1;
  } else {
    data.type = 2;
  }
  chatData.push(data);
});

socket.emit("joinRoom", roomName);
</script>

<style lang="sass" scoped>
/* 最外层高度 */
$outHeight: 650px
/* 边框颜色 */
$borderColor: #ebebeb
/* 气泡聊天框宽度 */
$chatDialogWidth: 500px

/* 聊天框占比 */
$chatFrameHeight: 70%
/* 输入框占比 */
$inputFrameHeight: 30%

:export
  outHeight: $outHeight

.chat
  height: 100vh

  .outBorder
    border: 1px solid
    border-radius: 5px
    border-color: $borderColor

  .tabs-box
    border-bottom: 1px solid
    border-color: $borderColor

  .title
    display: flex
    align-items: center
    justify-content: center

    height: 40px
    border-bottom: 1px solid
    border-color: $borderColor

  .bottom-box1
    width: 100%
    height: calc( $outHeight - 80px )
  .bottom-box2
    width: 100%
    height: calc( $outHeight - 80px )

  .bottom-left-box1
    height: 100%
    width: 100%

    .dialog-box
      height: $chatFrameHeight

      border-bottom: 1px solid
      border-color: $borderColor
      .dialog-box-in
        padding: 20px
    .input-box-out
      height: calc( $inputFrameHeight - 25px )

      .input-box
        height: calc( 100% - 58px)
        margin: 15px 0 10px 0

  .bottom-left-box2
    // height: calc( 100% - 38px )
    height: 100%
    width: 70%

    .dialog-box
      height: $chatFrameHeight

      border-right: 1px solid
      border-bottom: 1px solid
      border-color: $borderColor

    .input-box-out
      height: $inputFrameHeight
      border-right: 1px solid
      border-color: $borderColor

      .input-box
        height: calc( 100% - 38px)
        margin: 10px 0 5px 0

  .input-box
    height: 20%
    border-color: $borderColor

  .member-box
    height: 100%
    width: 30%

/* 气泡输入框 */
.dialog-box-my
  display: flex
  // justify-content: space-between

  .arrowbox-right
    position: relative
    margin: 0 15px
    padding: 10px
    max-width: $chatDialogWidth
    color: #555
    font-size: 16px
    background: #e0f2ff
    border-radius: 8px

    float: right
    clear: both

    word-wrap: break-word

  .arrowbox-right:before
    content: ""
    position: absolute
    // top: 50%
    top: 25px
    left: 100%
    margin-top: -15px
    border: 5px solid transparent
    border-left: 11px solid #e0f2ff

.dialog-box-other
  display: flex

  .arrowbox-left
    position: relative
    margin: 0 15px
    padding: 10px
    max-width: $chatDialogWidth
    color: #555
    font-size: 16px
    background: #e9e9e9
    border-radius: 8px

    word-wrap: break-word

  .arrowbox-left:before
    content: ""
    position: absolute
    // top: 50%
    top: 25px
    left: -14px
    margin-top: -15px
    border: 5px solid transparent
    border-right: 11px solid #e9e9e9

@media screen and (max-width: 600px)
  /* 当屏幕小于或等于 600px 时应用样式 */
  .outBorder
    width:100%
    height:100%

@media screen and (min-width: 600px)
  /* 当屏幕小于或等于 600px 时应用样式 */
  .outBorder
    min-width: 800px
    min-height: $outHeight
</style>
